/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../../inventoryinfo/goodsin_class/goodsInCom.vue"
// import purchase from "../purchase/purchase.vue";
import modelBody from "../purchase_not_mx/purchaseNotMx.vue"
import modelFooter from "../../customerinfo/q_client/client.vue";
import gridHeader from "@/components/print/selectTemplet.vue"

import {
  mapMutations
} from "vuex";
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: modelFooter
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    // printFn(){
    //   console.log("打印按钮",this.$refs.table.getSelected())
    //   if(this.$refs.table.getSelected().length!=1){
    //     return this.base.ElMessageFn('请选择一条单据')
    //   }
    //   // let ID = this.$refs.table.getSelected()[0].Stock_in
    //   // this.$refs.gridHeader.open(this.$route.name,ID)
    //    let row= this.$refs.table.getSelected()[0]
    //    console.log(this.$route)
    //   this.$refs.gridHeader.open(this.$route.name,row)
    // },
    ...mapMutations(
      ("salesContractMX", ["storeRemoveForm", "storeChangeForm"])
    ),
   
    //下面这些方法可以保留也可以删除
    async onInit() { //框架初始化配置前，
      this.queryFields = ['Supplier', 'CreateDate']
      this.textInline = false
      this.detailOptions.textInline = false
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == 'Attachment' || item.field == 'Image') {
            item.multiple = true;
            item.maxFile = 10;
          }
        })
      })
      this.detailEditOff = true
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      if (this.$route.path == "/q_stock_in" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.Supplier = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Voucher_sub',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      let butArr = [{
        name: "选择采购单商品",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          if (this.rowschild && this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }
          if (!this.editFormFields.Supplier) {
            this.base.ElMessageFn("请先选择供应商")
            return
          }
          let form = {
            Supplier: this.editFormFields.Supplier
          }
          this.storeChangeForm(form);

          if (this.editFormFields.WHSE_no) {
            this.$store.commit("setTabelText", true)
            // this.$refs.modelBody.open(this.editFormFields.Supplier, this.editFormFields.WHSE_Id[this.editFormFields.WHSE_Id.length - 1])
            this.$refs.modelBody.open(this.editFormFields.Supplier, this.editFormFields.WHSE_no)
          } else {
            this.base.ElMessageFn('请选择入库机构')
          }

        }
      }, {
        name: "选择商品",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          // let form = {
          //   AuditStatus: 1
          // }
          // this.storeChangeForm(form);
          if (this.rowschild && this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }
          // if (JSON.stringify(this.editFormFields.WHSE_Id) != "[]"&&this.editFormFields.WHSE_Id) {
          if (this.editFormFields.WHSE_no) {
            this.$store.commit("setTabelText", true)
            // this.$refs.modelHeader.detailOpen(this.editFormFields.WHSE_Id[this.editFormFields.WHSE_Id.length - 1])
            this.$refs.modelHeader.detailOpen(this.editFormFields.WHSE_no)
          } else {
            this.base.ElMessageFn('请选择入库机构')
          }
        }
      }]
      this.detailOptions.buttons.unshift(...butArr)

      this.detailOptions.columns.forEach(x => {
        if (x.field == 'WHSE_name') {
          x.filter = false
        }
        if (x.field == 'Tax_rate') {
          x.onChange = (column, row, tableData) => {
            // if (column.Goods_num) {
            //   this.getInventoryNum(column, column.Goods_num)
            // }
            if (!+column.Cost_price && column.Cost_price != undefined&& +column.Cost_price!==0) {
              row.Tax_exclusive = ""
              row.Total_price = ""
              this.base.ElMessageFn("成本价请输入有效数字")
              return
            }
            if (!+column.Goods_num && column.Goods_num != undefined) {
              row.Tax_exclusive = ""
              row.Total_price = ""
              this.base.ElMessageFn("数量请输入有效数字")
              return
            }
            if (column.Cost_price) {
              // column.Tax_exclusive = (column.Cost_price / (1 + +column.Tax_rate)).toFixed(4)
              const num = column.Cost_price / (1 + +column.Tax_rate)
              column.Tax_exclusive = this.base.roundToFourDecimals(num)
            }
            if (column.Cost_price && column.Goods_num) {
              // const num = column.Cost_price / (1 + +column.Tax_rate) * column.Goods_num
              let wsjg = column.Cost_price / (1 + +column.Tax_rate)
              wsjg = this.base.roundToFourDecimals(wsjg)
              let num = wsjg * column.Goods_num
              column.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)

            }
          }
        }
      })

    },
    async searchBefore(param) {
      // console.log(this.searchFormOptions)
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_stock_in" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Stock_in", param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Stock_in")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    async addBeforeAsync(formData) {
      this.storeRemoveForm()
      // return this.getSummary(formData)
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      // let boole = formData.detailData.some(item => item.Goods_num <= 0 || item.Goods_num == null)
      // let booleP = formData.detailData.some(item => item.Cost_price < 0 || item.Cost_price == null)
      // let booleP2 = formData.detailData.every(item => +item.Cost_price == true || item.Cost_price >= 0)

      // if (boole) {
      //   this.base.ElMessageFn("入库单明细中商品数量请大于零")
      //   return false;
      // }
      // if (booleP) {
      //   this.base.ElMessageFn("入库单明细中商品成本价请大于零")
      //   return false;
      // }
      // if (!booleP2) {
      //   this.base.ElMessageFn("入库单明细中商品成本价请填写有效数字")
      //   return false;
      // }
      // const WHSE_Id_val = JSON.stringify(this.editFormFields.WHSE_Id)
      // if (WHSE_Id_val == "[]" || WHSE_Id_val == "null") {
      //   this.base.ElMessageFn("请选择仓库")
      //   return false;
      // }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn("请选择入库机构")
        return false;
      }

      return this.testAdd(formData);
    },
    async updateBeforeAsync(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      this.storeRemoveForm()
      // let boole = formData.detailData.some(item => item.Goods_num <= 0 || item.Goods_num == null)
      // let booleP = formData.detailData.some(item => item.Cost_price < 0 || item.Cost_price == null)
      // let booleP2 = formData.detailData.every(item => +item.Cost_price == true || item.Cost_price >= 0)

      // if (boole) {
      //   this.base.ElMessageFn("入库单明细中商品数量请大于零")
      //   return false;
      // }
      // if (booleP) {
      //   this.base.ElMessageFn("入库单明细中商品成本价请大于零")
      //   return false;
      // } if (!booleP2) {
      //   this.base.ElMessageFn("入库单明细中商品成本价请填写有效数字")
      //   return false;
      // }
      // const WHSE_Id_val = JSON.stringify(this.editFormFields.WHSE_Id)
      // if (WHSE_Id_val == "[]" || WHSE_Id_val == "null") {
      //   this.base.ElMessageFn("请选择仓库")
      //   return false;
      // }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn("请选择入库机构")
        return false;
      }

      // return this.getSummary(formData)
      return this.testAdd(formData)
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id


      return true;
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      // if (JSON.stringify(this.editFormFields.WHSE_Id) == "[]" || JSON.stringify(this.editFormFields.WHSE_Id) == "null") {
      //   return false;
      // }

      if (!this.editFormFields.WHSE_no) return false;
      this.$refs.detail.$refs.table.toggleRowSelection(row);

      if (this.$route.path != "/q_stock_in" || this.rowAuditStatus != 0) {
        return
      } //|| !this.CreateUserBoole
      if (column.property == "Goods_num" || column.property == "Cost_price" || column.property == "WHSE_name" || column.property == "Remark") {//|| column.property == "Tax_rate" 
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      console.log(123, rows)
      console.log(this.$refs.detail.rowData.length)
      return true;
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      // console.log(this.filterPermission)
      // console.log(this.getTreeMenu)
      // console.log("permission",this.$store.state.permission)
      this.$store.commit("setTabelText", false)

      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_stock_in" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
        this.boxButtons[0].hidden = true
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
      if (this.rowAuditStatus == 0) { //&& !this.CreateUserBoole
        this.boxButtons[0].hidden = false
      }
    },
    modelOpenAfter(row) {
      this.rowschild = null
      let detailEdit = this.detailOptions.columns.filter(item => item.field == "Goods_num" || item.field == "Cost_price" )//|| item.field == "Tax_rate"
      if (this.detailEditOff) {
        this.detailEditType = {}
      }
      detailEdit.forEach(item => {
        if (this.detailEditOff) {
          const field = item.field
          const edit = item.edit
          this.detailEditType[field] = edit
        }
        // if (!this.CreateUserBoole) {
        //   item.edit = null
        // } else {
        //   const name = item.field
        //   item.edit = this.detailEditType[name]
        // }
      })
      this.detailEditOff = false


      //明细表点击表格时触发编辑方法
      this.detailOptions.beginEdit = (row, column, index) => {

        if (this.$route.path != "/q_stock_in" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
          return false
        }
        // const WHSE_Id_val = JSON.stringify(this.editFormFields.WHSE_Id)
        // if (WHSE_Id_val == "[]" || WHSE_Id_val == "null") {
        //   console.log("a")
        //   this.base.ElMessageFn("请选择仓库")
        //   return false;
        // }
        if (!this.editFormFields.WHSE_no) {
          this.base.ElMessageFn("请选择入库机构")
          return false;
        }

        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name") {
            if (!row.Goods_sub) {
              return
            }
            // let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
            // item.bind.data.forEach((d) => {
            //   d.hidden = true;
            // });
            // this.http.post(selectUrl, {}, "").then(reslut => {

            //   try {
            //     item.bind.data.forEach(d => {
            //       d.hidden = true
            //     })
            //     // if (reslut.rows.length) {
            //     //   item.bind.data.forEach(d => {
            //     //     reslut.rows.forEach(j => {
            //     //       if (d.key == j.WHSE_no) {
            //     //         d.hidden = false
            //     //       }
            //     //     })
            //     //   })
            //     // }
            //     if (reslut.length) {
            //       item.bind.data.forEach(d => {
            //         reslut.forEach(j => {
            //           if (d.key == j.WHSE_no) {
            //             d.hidden = false
            //           }
            //         })
            //       })
            //     }

            //   } catch (error) {
            //   }
            //   //回导致库位聚焦时，选中项变成第一个
            //   // row.WHSE_name = item.bind.data.filter(x => x.hidden == false)[0].key
            // })
            // this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_Id[this.editFormFields.WHSE_Id.length - 1])
            this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_no)
          }
        })
        // if (this.CreateUserBoole) {
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        this.rowschild = rows[0].childNodes[2]
        setTimeout(() => {
          // 成本价
          let testInputDom = rows[index].querySelectorAll("td")[7].querySelector("input")
          testInputDom.addEventListener("keyup", (e) => {
            if (!+e.target.value && +e.target.value!==0) {
              row.Tax_exclusive = ""
              row.Total_price = ""
              row.Tax_exclusive_total_price = ""
              this.base.ElMessageFn("成本价请输入有效数字")
              return
            }
            if (e.target.value <0) {
              row.Tax_exclusive = 0
              row.Total_price = 0
              row.Tax_exclusive_total_price = 0
              this.base.ElMessageFn("成本价请请输入正数")
              return
            }
            if (row.Tax_rate) {
              let num = e.target.value / (1 + +row.Tax_rate)
              row.Tax_exclusive = this.base.roundToFourDecimals(num)
            }
            if (!+row.Goods_num && row.Goods_num != undefined) {
              // row.Tax_exclusive = ""
              row.Total_price = ""
              this.base.ElMessageFn("数量请输入有效数字")
              return
            }
           
            if (row.Goods_num) {
              let num = e.target.value * row.Goods_num
              row.Total_price = this.base.roundToFourDecimals(num)
            }
            if (row.Tax_rate && row.Goods_num) {
              let wsjg = e.target.value / (1 + +row.Tax_rate)
              wsjg = this.base.roundToFourDecimals(wsjg)
              let num = wsjg * row.Goods_num
              row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)

            }
          })
          // 数量
          let testInputDom3 = rows[index].querySelectorAll("td")[6].querySelector("input")
          testInputDom3.addEventListener("keyup", (e) => {
            if (!+e.target.value && e.target.value != undefined) {
              row.Total_price = ""
              row.Tax_exclusive_total_price = ""
              this.base.ElMessageFn("数量请输入有效数字")
              return
            }
            if (!+row.Cost_price && row.Cost_price != undefined&& +row.Cost_price!==0) {
              row.Tax_exclusive = ""
              row.Total_price = ""
              this.base.ElMessageFn("成本价请输入有效数字")
              return
            }
            if (row.Tax_rate && row.Cost_price) {
              let wsjg = row.Cost_price / (1 + +row.Tax_rate)
              wsjg = this.base.roundToFourDecimals(wsjg)
              let num = wsjg * e.target.value
              row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
            }
            if (row.Cost_price) {
              row.Total_price = this.base.roundToFourDecimals(e.target.value * row.Cost_price)
            }
          })
        })
        // }

        return true
      }
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "WHSE_no") {
            x.onChange = () => {
              if (this.rowschild && this.$refs.detail.rowData.length) {
                this.rowschild.click()
              }
            }
          }
          if (x.field == "Supplier_key") {
            x.hidden = true
          }
          if (x.field != "Remark" && x.field != "Image" && x.field != "Attachment" && x.field != "WHSE_no"&& x.field != "Supplier") {
            x.disabled = true
            // if (x.field == "Supplier") {
            //   x.extra = {
            //     icon: "el-icon-zoom-in",
            //     text: "选择供应商",
            //     style: "color:#3a8ee6;font-size:13px;cursor:default",
            //     click: () => {
            //       this.$refs.modelFooter.open()
            //     }
            //   }
            // }
          } else {
            x.disabled = false
          }
          if (this.currentAction != 'Add' && x.field == "WHSE_no") {
            x.disabled = true
          }
          if (this.$route.path != "/q_stock_in" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
            // if (x.field == "Supplier") {
            //   x.extra = null
            // }
          }
        })
      })
    },
    updateAfter(result) { //编辑保存后result返回的状态及表单对象
      console.log("result", JSON.parse(result.data));
      return true;
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let num = 0
      let summaryPrc = 0
      let summaryPrc2 = 0
      let summaryNum = 0
      await detailRowData.forEach(item => {
        summaryPrc += +item.Total_price
        summaryPrc2 += +item.Tax_exclusive_total_price
        summaryNum += +item.Goods_num
        if (item.Goods_sub && item.Goods_name && item.Goods_num && item.WHSE_name) num++
      })
      // formData.mainData.Goods_num = summaryNum
      // formData.mainData.Total_price = this.base.roundToFourDecimals(summaryPrc)
      // // formData.mainData.Total_price = summaryPrc.toFixed(4)
      // formData.mainData.Tax_exclusive_total_price = summaryPrc2
      if (detailRowData.length == num) {
        return true
      } else {
        this.base.ElMessageFn("请正确选择商品")
        return false
      }
    },
    testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0)
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零或空")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }

      // let boole22 = formData.detailData.some(item => +item.Cost_price === 0)
      // if (boole22) {
      //   this.base.ElMessageFn("明细表中成本价不可为零或空")
      //   return false;
      // }
      // let boole11 = formData.detailData.some(item => item.Cost_price == "" || item.Cost_price == null || item.Cost_price == undefined)
      // if (boole11) {
      //   this.base.ElMessageFn("明细表中请填写成本价")
      //   return false;
      // }
      // let boole33 = formData.detailData.every(item => +item.Cost_price > 0 && +item.Cost_price)
      // if (!boole33) {
      //   this.base.ElMessageFn("明细表中成本价请填写有效正数")
      //   return false;
      // }
      let boole44 = formData.detailData.every(item => item.Tax_rate !== null && item.Tax_rate !== "")
      if (!boole44) {
        this.base.ElMessageFn("明细表中请选择税率")
        return false;
      }
      let boole1 = formData.detailData.some(item => item.Cost_price === "" || item.Cost_price === null || item.Cost_price === undefined)
      if (boole1) {
        this.base.ElMessageFn("明细表中请填写成本价")
        return false;
      }
      let boole22 = formData.detailData.every(item => item.Cost_price!==""||item.Cost_price!==null|| item.Cost_price === undefined||item.Cost_price?(""+item.Cost_price).trim()!=="":+item.Cost_price)
      if (!boole22) {
        this.base.ElMessageFn("明细表中成本价不可为空")
        return false;
      }
      let boole33 = formData.detailData.every(item => +item.Cost_price >= 0 )
      if (!boole33) {
        this.base.ElMessageFn("明细表中成本价请填写有效正数")
        return false;
      }

      let booleP3 = formData.detailData.every(item => item.Install_status != "" || item.Install_status != null)
      if (!booleP3) {
        this.base.ElMessageFn("明细表中请选择安装状态")
        return false;
      }
      return true
    },
  },

};
export default extension;